//
//  UIView+XHNClickBlcok.m
//  PockPower
//
//  Created by 邢行 on 2017/7/12.
//  Copyright © 2017年 XingHang. All rights reserved.
//

#import "UIView+XHNClickBlcok.h"
#import <objc/runtime.h>

static char kActionHandlerTapGestureKey;
static char kActionHandlerTapBlockKey;

@implementation UIView (XHNClickBlcok)

#pragma mark - 添加手势

- (void)addTapActionWithBlock:(GestureActionBlock)block
{
    self.userInteractionEnabled = YES;
    UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &kActionHandlerTapGestureKey);
    if (!gesture) {
        gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForTapGesture:)];
        [self addGestureRecognizer:gesture];
        objc_setAssociatedObject(self, &kActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    }
    objc_setAssociatedObject(self, &kActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
    
}

- (void)handleActionForTapGesture:(UITapGestureRecognizer*)gesture
{
    if (gesture.state == UIGestureRecognizerStateRecognized)
    {
        GestureActionBlock block = objc_getAssociatedObject(self, &kActionHandlerTapBlockKey);
        if (block)
        {
            block(gesture);
        }
    }
}

-(void)clickViewBlock:(GestureActionBlock)clickBlock{
    
    
    [self addTapActionWithBlock:clickBlock];
    
}


#pragma mark - 设置圆角(可以指定方向)

- (void)setCornerRadius:(CGFloat)radius
{
    [self setRoundedCorners:UIRectCornerAllCorners radius:radius];
}
- (void)setRoundedCorners:(UIRectCorner)corners radius:(CGFloat)radius
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}
@end
